package com.aerospace.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Aerospace
 * @Date: 2021/5/22 17:26
 * @Description: Dream begins
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        //线程池机制
        //1、创建一个线程池
        //2、如果有客户端连接，就创建一个线程，与之通讯（单独写一个方法）
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //创建服务端serversocket
        ServerSocket serverSocket = new ServerSocket(8099);
        System.out.println("服务启动了");
        while (true){
            System.out.println("主线程信息id = " + Thread.currentThread().getId() + "名字 = " + Thread.currentThread().getName());
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);
                }
            });

        }
    }

    //编写一个handler方法,和客户端通讯
    private static void handler(Socket socket) {
        try{
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            while(true){
                System.out.println("线程信息id=" + Thread.currentThread().getId() + "名字 = " + Thread.currentThread().getName());
                //循环从流里的数据读取byte数组长度的数据
                int readSize = inputStream.read(bytes);
                if(readSize != -1){
                    System.out.println(new String(bytes,0,readSize)); //输出客户端发出的数据
                }else {
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("关闭和client的连接");
            try{
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
